package com.cg.config;

import com.cg.param.WechatUrl;
import com.cg.util.WeiXinUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;


/**
 * @Author: cg
 * @Date: Create IN 2017/6/21 11:12
 * @Email: cg_666666@163.com
 */
@Configuration
@EnableScheduling
@EnableConfigurationProperties(WechatProperties.class)
public class TokenJob {
    @Autowired
    private StringRedisTemplate stringRedisTemplate; //这个报红没关系，一样可以用
    @Autowired
    private WechatProperties wechatProperties;
//每110分钟执行一次，启动先执行一次
    @Scheduled(fixedRate = 60*110*1000)
    public void wxTokentask(){
        ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
        //--------------------access_token--------------------------------
        String url1 = WechatUrl.ACCESS_TOKEN.replace("APPID", wechatProperties.getAppId()).replace("APPSECRET", wechatProperties.getSecret());
        JSONObject jsonObject = WeiXinUtils.httpsRequest(url1, "GET", null);
        String access_token=null;
        try {
             access_token = (String) jsonObject.get("access_token");
            System.out.println("更新Access_token:   "+access_token+"   "+new Date());
            ops.set("ACCESS_TOKEN",access_token);
        }catch (Exception e) {
          System.out.println("定时任务取access_token异常了:"+e);
        }
        //------------------js_api_ticket----------------------------
        String ticketurl=WechatUrl.JSAPI_TICKET.replace("ACCESS_TOKEN",access_token);
        JSONObject jsonObjecticket = WeiXinUtils.httpsRequest(ticketurl, "GET", null);
        try {
            String ticket = jsonObjecticket.getString("ticket");
            System.out.println("更新jsapiticket:   "+ticket+"   "+new Date());
            ops.set("JSAPI_TICKET",ticket);
        }catch (Exception e){
            System.out.println("定时任务设置ticket异常了:"+e);
        }

       //---------------api_card_ticket------------------------------------
        String cardurl = WechatUrl.API_CARD_TICKET.replace("ACCESS_TOKEN", access_token);
        JSONObject jsonObject1 = WeiXinUtils.httpsRequest(cardurl, "GET", null);
        try {
            String ticket = jsonObject1.getString("ticket");
            System.out.println("更新card_api_ticket:   "+ticket+"   "+new Date());
            ops.set("API_CARD_TICKET",ticket);
        }catch(Exception e){
            System.out.println("定时任务设置card_ticket异常了:"+e);
        }

    }
}
